<template>
	<div>
		<Row type="flex" justify="space-between" style="width: 90%;margin-left: 5%">
			<Col>
				<Button type="info" style="background:rgba(58,152,255,1);width: 80px" @click="endSession">{{ $t('ivcs.endsession') }}</Button>
			</Col>
			<Col>
				<Button type="info" style="background:rgba(58,152,255,1);width: 80px" @click="faceRecognition">{{ $t('ivcs.faceRecognition') }}</Button>
			</Col>
			<Col>
				<Button type="info" style="background:rgba(58,152,255,1);width: 80px" @click="snapshot">{{ $t('ivcs.screenshots') }}</Button>
			</Col>
			<Col>
				<Button type="info" style="background:rgba(58,152,255,1);width: 80px" @click="screen" v-show="screenPublicationId == null">{{ $t('ivcs.screenshare') }}</Button>
				<Button type="error" style="width: 80px" v-show="screenPublicationId" @click="stopScreenShare()">{{ $t('ivcs.screenshareend') }}</Button>
			</Col>

			<Col v-show="screenPublicationId && getCustomerClientInfo">
				<Button type="info" style="background:rgba(58,152,255,1);width: 80px;" v-show="screenPublicationId" @click="screenMark()">{{ $t('ivcs.screenmark') }}</Button>
			</Col>

			<Col>
				<Button type="info" style="background:rgba(58,152,255,1);width: 80px" @click="transfer">{{ $t('ivcs.transfer') }}</Button>
			</Col>
			<Col>
				<Button type="info" style="background:rgba(58,152,255,1);width: 80px" @click="three">{{ $t('ivcs.three') }}</Button>
			</Col>
		</Row>

		<div class="content">
			<div class="icon-left">
				<img :src="menuBtnNumbers === 4 ? require('../../static/images/left.png') : require('../../static/images/disableleft.png')" @click="leftArrow" :class="menuBtnNumbers === 4 ? 'allow' : 'disabled'" />
			</div>

			<ul class="btn-box">
				<template v-for="(item, index) in btns">
					<li :key="item.id" v-show="menuBtnNumbers == 6 ? index < menuBtnNumbers : index > menuBtnNumbers">
						<img class="icon" v-if="item.id != 7 && item.id != 10 && item.id != 11 && item.id != 9 && item.id != 2" :src="item.icon" @click="clickBtns(item.id)" />
						<img class="icon" v-if="item.id === 7" :src="isScreenRecording === true ? require('../../static/images/stopRecord.png') : require('../../static/images/record.png')" @click="clickBtns(item.id)" />
						<img :class="screenSyncState === 'disable' ? 'disabled' : 'allow'" v-if="item.id === 10" :src="screenSyncState === 'disable' ? require('../../static/images/screenSyncDisable.png') : screenSyncState === 'started' ? require('../../static/images/screenSyncing.png') : require('../../static/images/startScreenSync.png')" @click="clickBtns(item.id)" />
						<img class="icon" v-if="item.id === 11" :src="isScannerCode ? require('../../static/images/qrcodeing.png') : require('../../static/images/qrcode.png')" @click="clickBtns(item.id)" />
						<img :class="isLocationing ? 'disabled' : 'allow'" v-if="item.id === 9" :src="isLocationing ? require('../../static/images/locationgray.png') : require('../../static/images/location.png')" @click="clickBtns(item.id)" />
						<img class="icon" v-if="item.id === 2" :src="nowSendFormStatus === sendFormStatus.submit ? require('../../static/images/submitForm.png') : nowSendFormStatus === sendFormStatus.end ? require('../../static/images/stopSendForm.png') : require('../../static/images/form.png')" @click="clickBtns(item.id)" />
						<span v-if="item.id != 7 && item.id != 10 && item.id != 11 && item.id != 2">{{ $t(item.text) }}</span>
						<span v-if="item.id === 7">{{ btnRecordTitle }}</span>
						<span v-if="item.id === 10">{{ screenSyncTitle }}</span>
						<span v-if="item.id === 2">{{ sendFormTitle }}</span>
						<span v-if="item.id === 11">{{ scannerCodeTitle }}</span>
						<input style="display: none;" type="file" name="pdfFile" id="pdfFile" value="" accept=".pdf" @change="sendPdfFile($event)" v-if="item.id == 3" />
					</li>
				</template>
			</ul>
			<div class="icon-right">
				<img :src="menuBtnNumbers === 6 ? require('../../static/images/right.png') : require('../../static/images/disableright.png')" @click="rightArrow" :class="menuBtnNumbers === 6 ? 'allow' : 'disabled'" />
			</div>

			<!--发送表单弹框-->
			<Modal v-model="showFormView" :closable="true" :mask-closable="false" :title="$t('ivcs.form')" @on-cancel="onCancelShowFormView" style="width:70%">
				<Form :model="form" :rules="ruleValidate">
					<FormItem :label="$t('ivcs.pleaseSelectSendForm')" prop="name">
						<Select v-model="form.id" style="width:200px" :placeholder="$t('ivcs.pleaseSelectSendForm')">
							<Option v-for="item in formTemplateList" :value="item.id" :key="item.id">{{ item.name }}</Option>
						</Select>
					</FormItem>
				</Form>
				<div slot="footer">
					<Button type="info" size="default" class="defaultbackColor" @click="sendFormTemplate">{{ $t('ivcs.Yes') }}</Button>
				</div>
			</Modal>

			<MessageTips v-if="messageTipsModel.showMessageTips" :messageTipsModel="messageTipsModel" @cancel="cancel" @sumbit="sumbit"></MessageTips>
		</div>
	</div>
</template>

<script>
import ivcs from '../ivcs-sdk';
import { getFormNameByScenId, getFormFollowId, updateFormRecord } from '../api/api';
import MessageTips from './Toast/MessageTips.vue';
import { mapState } from 'vuex';
import { sendMessageToRecord } from '../tool/util';
import { uploadFile } from '../tool/uploadFile';
export default {
	name: 'AgentOp',
	data() {
		return {
			menuBtnNumbers: 6, //判断菜单显示6个
			showFormView: false,
			nowSendFormStatus: 'start',
			formName: '', //表单名称
			//判断推送表单状态
			sendFormStatus: {
				start: 'start',
				submit: 'ing',
				end: 'end'
			},
			followId: '', //表单流水号id
			form: {
				id: ''
			},
			formTemplateList: [],
			selectFormTemplate: null,
			//自定义弹窗内容
			messageTipsModel: {
				showMessageTips: false,
				title: '',
				content: '',
				btnText: ''
			},
			ruleValidate: {
				name: [{ required: true, message: 'The name cannot be empty', trigger: 'blur' }]
			},
			btns: [
				{
					id: 1,
					icon: require('../../static/images/camera.png'),
					text: 'ivcs.guide'
				},
				{
					id: 2,
					icon: require('../../static/images/form.png'),
					text: 'ivcs.form'
				},
				{
					id: 3,
					icon: require('../../static/images/file.png'),
					text: 'ivcs.pdf'
				},
				{
					id: 4,
					icon: require('../../static/images/hand.png'),
					text: 'ivcs.handsign'
				},
				{
					id: 5,
					icon: require('../../static/images/sendvideo.png'),
					text: 'ivcs.video'
				},
				{
					id: 6,
					icon: require('../../static/images/sendlink.png'),
					text: 'ivcs.link'
				},
				{
					id: 7,
					icon: require('../../static/images/record.png'),
					text: 'ivcs.screenrecording'
				},
				{
					id: 8,
					icon: require('../../static/images/inviteHelp.png'),
					text: 'ivcs.inviteOtherScreenShare'
				},
				{
					id: 9,
					icon: require('../../static/images/location.png'),
					text: 'ivcs.getlocation'
				},
				{
					id: 11,
					icon: require('../../static/images/qrcode.png'),
					text: 'ivcs.sendScannerCode'
				},
				{
					id: 10,
					icon: require('../../static/images/startScreenSync.png'),
					text: 'ivcs.startScreenSync'
				}
			]
		};
	},
	props: ['screenPublicationId', 'sessionId', 'screenRecordId', 'customerData', 'screenSyncState', 'isScreenRecording', 'isScannerCode', 'isLocationing', 'clientId', 'customerCallbizScenarioId', 'customerName', 'agentClientId', 'agentName', 'customerClientInfo'],
	components: {
		MessageTips
	},
	computed: {
		...mapState({
			messageData: state => state.message.messageData,
			agent: state => state.user.agent,
			customer: state => state.user.customer,
			cmdData: state => state.message.cmdData
		}),
		screenSyncTitle() {
			if (this.screenSyncState === 'started') {
				return this.$t('ivcs.stopScreenSync');
			} else if (this.screenSyncState === 'disable') {
				return this.$t('ivcs.startScreenSync');
			} else {
				return this.$t('ivcs.startScreenSync');
			}
		},
		sendFormTitle() {
			if (this.nowSendFormStatus === this.sendFormStatus.end) {
				return this.$t('ivcs.stopSendForm');
			} else if (this.nowSendFormStatus === this.sendFormStatus.sumbit) {
				return this.$t('ivcs.sumbitForm');
			} else {
				return this.$t('ivcs.form');
			}
		},
		btnRecordTitle() {
			if (this.isScreenRecording === true) {
				return this.$t('ivcs.stopRecord');
			} else {
				return this.$t('ivcs.screenrecording');
			}
		},
		scannerCodeTitle() {
			if (this.isScannerCode === true) {
				return this.$t('ivcs.stopScanneCode');
			} else {
				return this.$t('ivcs.sendScannerCode');
			}
		},
		/**2021-11-19 屏幕共享增加设别判断，android ios 不展示屏幕标注 */
		getCustomerClientInfo() {
			return this.customerClientInfo && this.customerClientInfo.toLowerCase() !== 'android' && this.customerClientInfo.toLowerCase() !== 'ios';
		}
	},
	mounted() {},
	methods: {
		//根据id触发不同的点击事件
		clickBtns(id) {
			switch (id) {
				case 1:
					this.photoGuideBox();
					break;
				case 2:
					this.sendform();
					break;
				case 3: {
					let pdf = document.getElementById('pdfFile');
					pdf.click();
					break;
				}
				case 4:
					this.handSign();
					break;
				case 5:
					this.sendVideoLink();
					break;
				case 6:
					this.sendPageLink();
					break;
				case 7:
					if (this.isScreenRecording === false) {
						this.recordScreen();
					} else {
						this.stopRecordScreen();
					}
					break;
				case 8:
					this.requestScreenShare();
					break;
				case 9:
					this.getlocation();
					break;
				case 10:
					this.startScreenSync();
					break;
				case 11:
					if (this.isScannerCode === false) {
						this.sendScanner();
					} else {
						this.stopSendScanner();
					}
					break;
				default:
					break;
			}
		},

		leftArrow() {
			this.menuBtnNumbers = 6;
		},

		rightArrow() {
			this.menuBtnNumbers = 4;
		},

		/**
		 * 发送信息记录
		 *
		 */
		sendMessageRecord(businessType, message, result, info, customerData, role) {
			let data = {};
			data.businessType = businessType ? businessType : '';
			data.message = message ? message : '';
			data.result = result ? result : { code: '', message: '' };
			data.info = info ? info : {};
			data.customerData = customerData ? customerData : this.customerData;
			data.agentData = this.$store.state.agentInfo ? this.$store.state.agentInfo : '';
			role ? role : 'all';
			ivcs.agent.sendCustomMessage(
				data,
				role,
				success => {
					console.log('发送消息成功！' + data, success);
				},
				error => {
					console.log('发送消息失败！' + data, error);
				}
			);
		},

		photoGuideBox() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('photoGuideBox');
		},

		sendVideoLink() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('sendVideoLink');
		},

		sendPageLink() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('sendPageLink');
		},

		snapshot() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('snapshot');
		},

		handSign() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('handSign');
		},

		getlocation() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('getlocation');
		},

		//二维码
		sendScanner() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('sendScanner');
		},

		//停止推送二维码
		stopSendScanner() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('stopSendScanner');
		},

		//关闭选择发送的表单弹窗
		onCancelShowFormView() {
			this.showFormView = false;
		},

		//发送表单
		async sendFormTemplate() {
			let data = {
				org: this.$store.state.agentInfo.org,
				fromClientId: this.agentClientId,
				toClientId: this.clientId,
				templateId: this.form.id,
				sessionId: this.sessionId
			};
			let formId = '';
			//生成表单流水号
			try {
				let date = await getFormFollowId(data);
				this.followId = date.data.data.followId;
				formId = date.data.data.id;
			} catch (e) {
				console.log(e);
			}
			this.currentForm = this.formTemplateList.find(item => item.id === this.form.id);
			let formData = {
				followId: this.followId,
				formTemplate: this.form.id,
				formName: this.currentForm.name,
				formId: formId,
				from: this.agentName || '',
				to: this.customerName || ''
			};
			this.$store.state.formDataId = this.form.id;
			this.$store.state.formDataName = this.currentForm.name;
			this.$store.state.submitFormId = formId;
			ivcs.agent.sendOnlineForm(
				formData,
				this.customer.clientId,
				resp => {
					this.nowSendFormStatus = this.sendFormStatus.end; //改变按钮状态
					console.log('send form success', resp);
					this.cmdData.set('fill-form', resp.cmdId);
					this.showFormView = false;
					this.$Message.success(this.$t('ivcs.sheet') + '&lt;' + this.currentForm.name + '&gt;' + this.$t('ivcs.sendFormMessageTips') + '&lt;' + this.customerName + '&gt;');
					let data = {};
					data.cmd = 'fill-form';
					let msg = sendMessageToRecord('fill-form', { cmd: 'fill-form', data: {} }, this.agent);
					this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
				},
				function(error) {
					console.log('send form error', error);
					this.$Message.error(error);
				}
			);
			console.log('send form data', formData);
		},
		//获取该业务场景下的表单
		async sendform() {
			this.form.id = '';
			if (this.nowSendFormStatus === this.sendFormStatus.submit) {
				return;
			}
			if (this.operatingJudgment() === 0) {
				return;
			}
			if (this.nowSendFormStatus === this.sendFormStatus.start) {
				try {
					//获取表单名称
					let data = await getFormNameByScenId(this.customerCallbizScenarioId);
					this.formTemplateList = data.data.result.map(item => ({ id: item.formTemplate.id, name: item.formTemplate.name, flieds: item.formTemplate.fields }));
					this.showFormView = true;
				} catch (e) {
					console.log(e);
				}
			} else {
				//警告弹窗tips
				this.messageTipsModel = {
					showMessageTips: true,
					title: this.$t('ivcs.stopSendForm'),
					content: this.$t('ivcs.stopWriteFormConeten'),
					btnText: this.$t('ivcs.stopWriteFormBtn')
				};
			}
		},

		//弹窗关闭事件
		cancel() {
			this.messageTipsModel.showMessageTips = false;
			this.showMessageTips = false;
		},

		//终止填写事件
		sumbit() {
			this.nowSendFormStatus = this.sendFormStatus.start;
			this.messageTipsModel.showMessageTips = false;
			let cmdId = this.cmdData.get('fill-form');
			ivcs.agent.cancelOnlineForm(
				cmdId,
				this.customer.clientId,
				s => {
					let date = {
						id: this.$store.state.submitFormId,
						status: 'fail'
					};
					this.updateFormRecord(date);
					this.$Message.error(this.$t('ivcs.clientId') + '&lt;' + this.customerName + '&gt;' + this.$t('ivcs.nowWriteForm') + '&lt;' + this.currentForm.name + '&gt;' + this.$t('ivcs.endForm') + this.$t('ivcs.sumbiterror'));
					let record = {};
					record.formName = this.currentForm.name;
					console.log('cancelOnlineForm send-form success', s);
					let msg = sendMessageToRecord('peer-cancel', { cmd: 'fill-form', data: {} }, this.agent);
					this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
				},
				e => {
					this.sendMessageRecord('system_msg', 'stop send form error', e);
					console.log('cancelOnlineForm send-form error', e);
				}
			);
		},

		//更新表单提交记录
		async updateFormRecord(data) {
			try {
				let record = await updateFormRecord(data);
				console.log(record);
			} catch (e) {
				console.log(e, '更新表单记录失败');
			}
		},

		recordScreen() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('recordScreen');
		},

		stopRecordScreen() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('stopRecordScreen');
		},

		requestScreenShare() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('requestScreenShare');
		},
		// 发起同屏辅助
		startScreenSync() {
			if (this.screenSyncState === 'disable') return;
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('startScreenSync');
		},

		async sendPdfFile(event) {
			if (this.operatingJudgment() === 0) {
				return;
			}
			var file = document.getElementById('pdfFile').files[0];
			var fileSize = file.size;
			var fileType = file.type;
			console.log('pdf file filesize and fileType,', fileSize, fileType);
			if (fileSize > maxUploadFileSize) {
				this.$Message.error(this.$t('ivcs.exceedingTheSizeLimit'));
				event.target.value = null;
				return;
			}
			if (fileType != 'application/pdf') {
				this.$Message.error(this.$t('ivcs.fileTypeError'));
				event.target.value = null;
				return;
			}

			let data = await uploadFile(file);
			if (data) {
				ivcs.agent.sendViewResource(
					{ type: 'paper', ...data },
					this.customer.clientId,
					resp => {
						console.log(resp);
						this.$Message.success(this.$t('session.success'));
						let msg = sendMessageToRecord('view', { cmd: 'view', data }, this.agent);
						this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
					},
					error => {
						console.log(error);
						this.$Message.error(error);
					}
				);
			}
			event.target.value = null;
		},

		stopScreenShare() {
			this.$emit('stopScreenShare');
		},

		screenMark() {
			this.$emit('screenMark');
		},

		endSession() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('endSession');
		},

		faceRecognition() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('faceRecognition');
		},

		screen() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('screen');
		},

		transfer() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('transfer');
		},

		three() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			this.$emit('three');
		},

		operatingJudgment() {
			if (this.sessionId == null) {
				this.$Message.error(this.$t('ivcs.nosession'));
				return 0;
			}
			if (this.screenPublicationId) {
				var self = this;
				this.$Notice.error({
					title: self.$t('ivcs.confirm'),
					desc: self.$t('ivcs.sharewarn'),
					duration: 10
				});
				return 0;
			}
			return 1;
		}
	}
};
</script>

<style scoped>
.icon-right {
	width: 16%;
}

.icon-left {
	width: 16%;
}

.allow {
	cursor: pointer;
}

.disabled {
	cursor: not-allowed;
}

.btn-box li img {
	width: 90%;
}

.icon {
	cursor: pointer;
}

.btn-box li {
	display: flex;
	flex-flow: column;
	align-items: center;
	margin-top: 20px;
	margin-left: 10px;
	margin-right: 10px;
	width: 16.66%;
}

ul {
	display: flex;
	align-items: flex-start;
	justify-content: center;
}

.content {
	margin: 40px 10px;
	/* min-width: 570px; */
	min-height: 140px;
	background: rgba(255, 255, 255, 1);
	box-shadow: 5px 7px 49px 5px rgba(44, 137, 234, 0.13);
	border-radius: 10px;
	display: flex;
	justify-content: space-around;
	align-items: center;
}

.col {
	display: flex;
	flex-direction: column;
	align-content: center;
	align-items: center;
	margin-top: 30px;
	margin-left: 10px;
	margin-right: 10px;
}

.title {
	width: 60px;
	height: 20px;
	font-size: 10px;
	font-family: PingFang SC;
	font-weight: 300;
	color: rgba(51, 51, 51, 1);
	line-height: 20px;
	margin-top: 0px;
}
</style>
